package com.mobileClientKernel.android.commonLayer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class JJEncrypt {


    public static Object byte2Obj(byte[] bytes) {
        Object result = null;
        ByteArrayInputStream paIptStream = new ByteArrayInputStream(bytes);
        try {
            ObjectInputStream objIptStream = new ObjectInputStream(paIptStream);
            result = objIptStream.readObject();
            paIptStream.close();
            objIptStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return result;
    }

    public static byte[] obj2Byte(Object obj) {
        byte[] result = null;
        ByteArrayOutputStream baOptStream = new ByteArrayOutputStream();
        try {
            ObjectOutputStream objOptStream = new ObjectOutputStream(baOptStream);
            objOptStream.writeObject(obj);
            result = baOptStream.toByteArray();

            objOptStream.close();
            baOptStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    public static void writeObj2File(Object obj, String fileName) {
        File file = new File(fileName);
        try {
            FileOutputStream outputStream = new FileOutputStream(file);
            byte[] objByte = obj2Byte(obj);
            objByte = DESUtil.encryptDes(objByte, getKey()); //对字节流加密
            outputStream.write(objByte);
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Object readObjfromFile(String fileName) {
        File file = new File(fileName);
        Object object = null;
        try {
            FileInputStream inputStream = new FileInputStream(file);
            int length = inputStream.available();
            byte[] byteObj = new byte[length];
            inputStream.read(byteObj);
            byteObj = DESUtil.decryptDes(byteObj,getKey()); //对字节流加密
            object = byte2Obj(byteObj);     //字節流轉對象
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return object;
    }

    public static String getKey(){
        return "(7Bg[#Kj";
    }
}
